import Vue from 'vue';
import Router from 'vue-router';
import iView from 'iview';

Vue.use(Router);

const router = new Router({
    mode: 'history',
    base: __dirname
});

router.beforeEach((to, from, next) => {
    //console.log('beforeEach');
    iView.LoadingBar.start();
    next();
});

router.afterEach((route) => {
    //console.log('afterEach');
    iView.LoadingBar.finish();
    window.scrollTo(0, 0);
});

router.onReady(callback => {
    console.log('onReady');
});

router.onError((callback) => {
    console.log('onError');
});

//路由去中心化
let minLength = 3;
let maxLength = 3;
let routes = [];
let routerObj = {};
let routerChildrenObj = {}; 
const routerContext = require.context('../views/', true, /router\.js$/)

routerContext.keys().map(function(key){
    //console.log(38,key,routerContext(key));
    if (routerContext(key).default) {
        checkChildren(key);
    } else {
        console.log('the path '+key+'  is error');
    }
});

//提取目录路由数组
function checkChildren(key) {
    let routerModuleObj = routerContext(key).default,
        pathArr = key.split('/'),
        parentName = '',
        selfName = pathArr[pathArr.length-2];

    maxLength = pathArr.length > maxLength ?  pathArr.length : maxLength;

    if(pathArr.length > 3) {
        parentName = pathArr[pathArr.length-3];
    }

    routerObj[selfName] = {
        level : pathArr.length,
        selfName : selfName,
        parentName : parentName,
        component : routerModuleObj
    };
}

//构建层级
for (let i = maxLength; i > minLength; i--) {
    for (let j in routerObj) {
        if (routerObj[j].level == i) {
            if (routerObj[j].parentName) {
                let parentName = routerObj[j].parentName;
                let component = routerObj[parentName].component;
                if (!component.children) {
                    component.children = [];
                }
                component.children.push(routerObj[j].component);
            } else {
                console.log('error on router config');
            }
        }
    }
}

//构建路由
for (let j in routerObj) {
    if (routerObj[j].level == minLength) {
        routes.push(routerObj[j].component);
    }
}

console.log('路由',routes);

router.addRoutes(routes);

export default router;